package top.wyloop.util.password;

import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import java.security.SecureRandom;
import java.security.spec.KeySpec;

public class DESUtil {
    private static final String ALGORITHM = "DES";

    /**
     * 加密方法
     *
     * @param plaintext 明文
     * @param keyString 密钥
     * @return 密文
     */
    public static String encrypt(String plaintext, String keyString) {
        try {
            // 创建密钥对象
            KeySpec keySpec = new DESKeySpec(keyString.getBytes());     // spec - specification
            SecretKeyFactory factory = SecretKeyFactory.getInstance(ALGORITHM);
            SecretKey key = factory.generateSecret(keySpec);

            // 创建密码对象并设置为加密模式，加密
            SecureRandom seed = new SecureRandom();
            Cipher cipher = Cipher.getInstance("DES");
            cipher.init(Cipher.ENCRYPT_MODE, key, seed);
            return new Base64().encodeToString(cipher.doFinal(plaintext.getBytes()));    // byte[] --> String
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * 解密方法
     *
     * @param ciphertext 密文
     * @param keyString  密钥
     * @return 明文
     */
    public static String decrypt(String ciphertext, String keyString) {
        try {
            // 创建密钥对象
            KeySpec keySpec = new DESKeySpec(keyString.getBytes());
            SecretKeyFactory factory = SecretKeyFactory.getInstance(ALGORITHM);
            SecretKey key = factory.generateSecret(keySpec);

            // 创建密码对象并设置为解密模式，解密
            SecureRandom seed = new SecureRandom();
            Cipher cipher = Cipher.getInstance("DES");
            cipher.init(Cipher.DECRYPT_MODE, key, seed);
            return new String(cipher.doFinal(Base64.decodeBase64(ciphertext)));    // String --> byte[]
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }
}
